package org.changs.message;

import android.app.AlertDialog;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.message.databinding.ItemMsgBinding;
import org.changs.message.push.IotPushPresenter;

import aplug.utils.SwipeItemDelegate;

/**
 * Created by Administrator on 2017/9/12.
 */

public class MsgAdapter extends SimpleAdapter<PushMsg, ItemMsgBinding> {
    private SwipeItemDelegate delegate;
    private Context context;
    private IotPushPresenter presenter;

    public MsgAdapter(Context context, RecyclerView rcyView, IotPushPresenter presenter) {
        super(R.layout.item_msg);
        this.presenter = presenter;
        this.context = context;
        delegate = new SwipeItemDelegate(this, rcyView);
    }

    @Override
    public void onBindViewHolder(ItemMsgBinding binding, int position) {
        delegate.setDelegate(binding.swipeLayout);
        PushMsg pushMsg = getData().get(position);

        if (pushMsg.getMsgType().equals("2")) {
            binding.image.setImageResource(R.mipmap.icon_msg_map);
        } else if (pushMsg.getMsgType().equals("1")) {//1：系统升级
            binding.image.setImageResource(R.mipmap.icon_msg_update);
        }
        binding.tvName.setText(pushMsg.getMsgTitle());
        binding.tvContent.setText(pushMsg.getMsgContent());

        binding.btnDelete.setOnClickListener(v -> showDialog(pushMsg));
    }

    private AlertDialog dialog;

    private void showDialog(PushMsg pushMsg) {
        if (dialog == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_delete, null);
            dialog = new AlertDialog.Builder(context).setView(view).create();
            view.findViewById(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
        }
        dialog.show();
        dialog.findViewById(R.id.btn_confirm).setOnClickListener(v -> {
            presenter.delete(pushMsg);
            dialog.dismiss();
            delegate.closeOpenedSwipeItemLayoutWithAnim();
        });
    }
}
